import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hsh/pages/test/test_logic.dart';
import 'package:get/get.dart';
import '../../brick/widget/text_widget.dart';
import '../../fluttergromore/ads/ad_feed_view.dart';
import '../../fluttergromore/ads/ads_utils.dart';
import '../../fluttergromore/api/api_service.dart';
import '../../fluttergromore/plugin/ts_plugin.dart' show TsPlugin;
import '../../fluttergromore/usersp/user_sp.dart';
import '../../fluttergromore/utils/device_package_info.dart';
import '../../style/style.dart';
import 'JsonViewerWithLineBreaks.dart';

class TestPage extends StatelessWidget {
  TestPage({Key? key}) : super(key: key);
  final logic = Get.put(TestLogic(), permanent: true);

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.dark,
      child: Scaffold(
        backgroundColor: const Color(0xFFEEEEEE),
        appBar: AppBar(
          title: const Text("测试"),
        ),
        body: SafeArea(
          child: SingleChildScrollView(
            child: Column(
              children: [
                Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    InkWell(
                      onTap: () {
                        ApiService().appInstall().then((value) {
                          Get.dialog(
                            Center(
                              child: JsonViewerFixedLineBreaks(
                                jsonString: json.encode(value?.data),
                                fontSize: 14,
                                indentSpaces: 2,
                              ),
                            ),
                          );
                        });
                      },
                      child: Row(
                        children: [
                          const SizedBox(
                            width: 16,
                          ),
                          UIText(
                            text: 'install',
                            textColor: kAppColor("#333333"),
                            fontSize: 16,
                          ),
                          const Expanded(
                            flex: 1,
                            child: SizedBox(),
                          ),
                          const Icon(
                            Icons.keyboard_arrow_right_sharp,
                            color: Colors.grey,
                            size: 24,
                          )
                        ],
                      ),
                    ).paddingAll(12),
                    InkWell(
                      onTap: () {
                        ApiService().getAppConfig().then((value) {
                          Get.dialog(
                            Center(
                              child: JsonViewerFixedLineBreaks(
                                jsonString: json.encode(value?.data),
                                fontSize: 14,
                                indentSpaces: 2,
                              ),
                            ),
                          );
                        });
                      },
                      child: Row(
                        children: [
                          const SizedBox(
                            width: 16,
                          ),
                          UIText(
                            text: 'getAppConfig',
                            textColor: kAppColor("#333333"),
                            fontSize: 16,
                          ),
                          const Expanded(
                            flex: 1,
                            child: SizedBox(),
                          ),
                          const Icon(
                            Icons.keyboard_arrow_right_sharp,
                            color: Colors.grey,
                            size: 24,
                          )
                        ],
                      ),
                    ).paddingAll(12),
                    InkWell(
                      onTap: () async {
                        var oaId = await TsPlugin.getOaId();
                        var oaIdU = await TsPlugin.getOaIdH();
                        var oaIdH = await TsPlugin.getOaIdU();
                        Get.dialog(
                          Center(
                            child: JsonViewerFixedLineBreaks(
                              jsonString: json.encode({
                                "oaId": oaId,
                                "oaIdU": oaIdU,
                                "oaIdH": oaIdH,
                              }),
                              fontSize: 14,
                              indentSpaces: 2,
                            ),
                          ),
                        );
                      },
                      child: Row(
                        children: [
                          const SizedBox(
                            width: 16,
                          ),
                          UIText(
                            text: 'oaid',
                            textColor: kAppColor("#333333"),
                            fontSize: 16,
                          ),
                          const Expanded(
                            flex: 1,
                            child: SizedBox(),
                          ),
                          const Icon(
                            Icons.keyboard_arrow_right_sharp,
                            color: Colors.grey,
                            size: 24,
                          )
                        ],
                      ),
                    ).paddingAll(12),
                    InkWell(
                      onTap: () async {
                        var appId =
                            (await UserSp.instance.getAppConfig())?.appId ?? "";
                        var dInfo = DevicePackageInfo.instance;
                        Map<String, Object> map = {
                          "appId": appId,
                          "androidId": await dInfo.getId() ?? "",
                          "appVersion": await dInfo.getAppVersion(),
                          "pkgName": await dInfo.getPackageName(),
                          //设备品牌
                          "deviceBrand": await dInfo.getBrand() ?? "",
                          //"deviceIp": await TsPlugin.getIPAddress(),
                          //"deviceIp6": await TsPlugin.getLocalIpV6(),
                          //设备等级
                          "deviceLevel": 1,
                          //IOS广告标示符
                          "idfa": "",
                          //首次安装时间，时间戳（秒）
                          "installDatetime":
                              (DateTime.now().millisecondsSinceEpoch ~/ 1000)
                                  .toInt(),

                          ///匿名设备标识符
                          "oaId": await UserSp.instance.getOaId(),
                          "oaIdU": await UserSp.instance.getOaIdU(),
                          "oaIdH": await UserSp.instance.getOaIdH(),

                          //MAC地址
                          "mac": await TsPlugin.getMacFromHardware(),
                          //入网类型：0：WIFI、1：4G、2：5G
                          "networkAccess": await TsPlugin.getNetworkType(),
                          //操作系统, 0：Android、1：iOS 2.鸿蒙
                          "os": await TsPlugin.getSystemCode(),
                          if ((await TsPlugin.getSystemCode()) == 2)
                            "idfv": await TsPlugin.getSystemVersion(),
                          "resolution":
                              "${await dInfo.widthPx()}x${await dInfo.heightPx()}",
                          //0:未充电、1:充电
                          "charge": await TsPlugin.isBatteryCharging() ? 1 : 0,
                          //设备品牌
                          "deviceModel": await TsPlugin.getBrand(),
                          //设备状态，0：正常、1：异常
                          "deviceStatus": 0,
                          //设备异常标签，正常、代理、异常、模拟器、root、无SIM
                          "deviceTag": await TsPlugin.getRiskInfo(),
                          //操作系统版本
                          "osVersion": (await TsPlugin.getSystemCode()) == 2
                              ? await TsPlugin.getHarmonyVersion()
                              : await TsPlugin.getSystemVersion(),
                          //设备分辨率
                          "downloadChannel": await TsPlugin.getChannel(),
                          "carrier": await TsPlugin.getSimOperator(),
                          //设备运营商，0：移动、1：联通、2：电信,
                          "uaWebView": await TsPlugin.getWebViewUserAgent(),
                          "uaApp": await TsPlugin.getAppUserAgent(),
                          "imei": await TsPlugin.getImei(),
                          "meid": await TsPlugin.getPhoneMEID(),
                          "deviceId": await TsPlugin.getDeviceId(),
                          "deviceApps": "",
                        };
                        Get.dialog(
                          Center(
                            child: JsonViewerFixedLineBreaks(
                              jsonString: json.encode(map),
                              fontSize: 14,
                              indentSpaces: 2,
                            ),
                          ),
                        );
                      },
                      child: Row(
                        children: [
                          const SizedBox(
                            width: 16,
                          ),
                          UIText(
                            text: '设备信息获取',
                            textColor: kAppColor("#333333"),
                            fontSize: 16,
                          ),
                          const Expanded(
                            flex: 1,
                            child: SizedBox(),
                          ),
                          const Icon(
                            Icons.keyboard_arrow_right_sharp,
                            color: Colors.grey,
                            size: 24,
                          )
                        ],
                      ),
                    ).paddingAll(12),
                    InkWell(
                      onTap: () {
                        AdsUtils.showSplashAd();
                      },
                      child: Row(
                        children: [
                          const SizedBox(
                            width: 16,
                          ),
                          UIText(
                            text: '开屏',
                            textColor: kAppColor("#333333"),
                            fontSize: 16,
                          ),
                          const Expanded(
                            flex: 1,
                            child: SizedBox(),
                          ),
                          const Icon(
                            Icons.keyboard_arrow_right_sharp,
                            color: Colors.grey,
                            size: 24,
                          )
                        ],
                      ),
                    ).paddingAll(12),
                    InkWell(
                      onTap: () {
                        AdsUtils.showInterstitialAd();
                      },
                      child: Row(
                        children: [
                          const SizedBox(
                            width: 16,
                          ),
                          UIText(
                            text: '插屏',
                            textColor: kAppColor("#333333"),
                            fontSize: 16,
                          ),
                          const Expanded(
                            flex: 1,
                            child: SizedBox(),
                          ),
                          const Icon(
                            Icons.keyboard_arrow_right_sharp,
                            color: Colors.grey,
                            size: 24,
                          )
                        ],
                      ),
                    ).paddingAll(12),
                    InkWell(
                      onTap: () {
                        Get.dialog(
                          const Center(
                            child: MyAdFeedView(),
                          ),
                        );
                      },
                      child: Row(
                        children: [
                          const SizedBox(
                            width: 16,
                          ),
                          UIText(
                            text: '信息流',
                            textColor: kAppColor("#333333"),
                            fontSize: 16,
                          ),
                          const Expanded(
                            flex: 1,
                            child: SizedBox(),
                          ),
                          const Icon(
                            Icons.keyboard_arrow_right_sharp,
                            color: Colors.grey,
                            size: 24,
                          )
                        ],
                      ),
                    ).paddingAll(12),
                    InkWell(
                      onTap: () {
                        AdsUtils.showRewardVideoAd();
                      },
                      child: Row(
                        children: [
                          const SizedBox(
                            width: 16,
                          ),
                          UIText(
                            text: '激励视频',
                            textColor: kAppColor("#333333"),
                            fontSize: 16,
                          ),
                          const Expanded(
                            flex: 1,
                            child: SizedBox(),
                          ),
                          const Icon(
                            Icons.keyboard_arrow_right_sharp,
                            color: Colors.grey,
                            size: 24,
                          )
                        ],
                      ),
                    ).paddingAll(12),
                  ],
                ).paddingOnly(left: 16, right: 16).marginOnly(top: 30),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class JsonHighlighter extends StatelessWidget {
  final dynamic jsonData;
  final double fontSize;
  final int indentSpaces;

  JsonHighlighter({
    Key? key,
    required this.jsonData,
    this.fontSize = 14.0,
    this.indentSpaces = 2,
  }) : super(key: key);

  final Map<String, dynamic> sampleJson = {
    "name": "Flutter JSON Viewer",
    "version": 1.0,
    "isProduction": false,
    "features": ["Syntax Highlighting", "Pretty Formatting", "Scrollable View"],
    "settings": {"theme": "dark", "fontSize": 14, "indentation": 2}
  };

  // 格式化JSON并添加语法高亮
  RichText _buildHighlightedJson() {
    final String jsonString = json.encode(jsonData);

    List<TextSpan> children = [];
    final RegExp regex = RegExp(
      r'"(.*?)"|(\d+)|(true|false|null)|([{}[\],:])|(//.*)|(/\*[\s\S]*?\*/)',
      dotAll: true,
    );

    for (final match in regex.allMatches(jsonString)) {
      String? text = match.group(0);
      if (text == null) continue;

      Color? color;
      FontWeight? fontWeight;

      // 键名 - 绿色
      if (match.group(1) != null &&
          match.start > 0 &&
          jsonString[match.start - 1] == '"') {
        color = Colors.greenAccent;
        fontWeight = FontWeight.bold;
      }
      // 字符串值 - 黄色
      else if (match.group(1) != null) {
        color = Colors.yellowAccent;
      }
      // 数字 - 青色
      else if (match.group(2) != null) {
        color = Colors.cyanAccent;
      }
      // 布尔值和null - 紫色
      else if (match.group(3) != null) {
        color = Colors.purpleAccent;
      }
      // 括号和符号 - 白色
      else if (match.group(4) != null) {
        color = Colors.white;
        fontWeight = FontWeight.bold;
      }

      children.add(TextSpan(
        text: text,
        style: TextStyle(
          color: color ?? Colors.white,
          fontWeight: fontWeight,
          fontSize: fontSize,
        ),
      ));
    }

    return RichText(
      text: TextSpan(
        style: TextStyle(
          fontFamily: 'monospace',
          fontSize: fontSize,
        ),
        children: children,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      color: Colors.black87, // 深色背景增强对比度
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: SingleChildScrollView(
          child: _buildHighlightedJson(),
        ),
      ),
    );
  }
}

enum JsonViewerTheme { dark, light }

class CompatibleJsonViewer extends StatefulWidget {
  final String jsonString;
  final double fontSize;
  final int indentSpaces;
  final JsonViewerTheme theme;

  const CompatibleJsonViewer({
    Key? key,
    required this.jsonString,
    this.fontSize = 14.0,
    this.indentSpaces = 2,
    this.theme = JsonViewerTheme.dark,
  }) : super(key: key);

  @override
  _CompatibleJsonViewerState createState() => _CompatibleJsonViewerState();
}

class _CompatibleJsonViewerState extends State<CompatibleJsonViewer> {
  dynamic _jsonData;
  String? _errorMessage;
  bool _isCopied = false;

  @override
  void initState() {
    super.initState();
    _parseJson();
  }

  @override
  void didUpdateWidget(covariant CompatibleJsonViewer oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.jsonString != widget.jsonString) {
      _parseJson();
    }
  }

  void _parseJson() {
    try {
      _jsonData = json.decode(widget.jsonString);
      _errorMessage = null;
    } catch (e) {
      _jsonData = null;
      if (e is FormatException) {
        _errorMessage = 'JSON格式错误: ${e.message}\n错误位置: ${e.offset}';
      } else {
        _errorMessage = '解析失败: $e';
      }
    }
    setState(() {});
  }

  // 自定义JSON格式化方法，不依赖indent参数
  String _formatJson(dynamic jsonData, int indentLevel) {
    if (jsonData == null) return "null";

    String indent = " " * (indentLevel * widget.indentSpaces);
    String nextIndent = " " * ((indentLevel + 1) * widget.indentSpaces);

    if (jsonData is Map) {
      if (jsonData.isEmpty) return "{}";

      String result = "{\n";
      List<dynamic> keys = jsonData.keys.toList();

      for (int i = 0; i < keys.length; i++) {
        dynamic key = keys[i];
        dynamic value = jsonData[key];
        bool isLast = i == keys.length - 1;

        result += "$nextIndent\"$key\": ${_formatJson(value, indentLevel + 1)}"
            "${isLast ? "" : ","}\n";
      }

      result += "$indent}";
      return result;
    } else if (jsonData is List) {
      if (jsonData.isEmpty) return "[]";

      String result = "[\n";

      for (int i = 0; i < jsonData.length; i++) {
        bool isLast = i == jsonData.length - 1;
        result += "$nextIndent${_formatJson(jsonData[i], indentLevel + 1)}"
            "${isLast ? "" : ","}\n";
      }

      result += "$indent]";
      return result;
    } else if (jsonData is String) {
      return "\"${jsonData.replaceAll("\"", "\\\"")}\"";
    } else if (jsonData is bool) {
      return jsonData ? "true" : "false";
    } else {
      return jsonData.toString();
    }
  }

  Future<void> _copyToClipboard() async {
    await Clipboard.setData(ClipboardData(text: widget.jsonString));
    setState(() {
      _isCopied = true;
    });
    Future.delayed(const Duration(seconds: 2), () {
      if (mounted) {
        setState(() {
          _isCopied = false;
        });
      }
    });
  }

  RichText _buildHighlightedJson() {
    // 使用自定义格式化方法替代json.encode的indent参数
    final String jsonString = _formatJson(_jsonData, 0);

    final themeColors = _getThemeColors();

    List<TextSpan> children = [];
    final RegExp regex = RegExp(
      r'"(.*?)"|(\d+)|(true|false|null)|([{}[\],:])',
      dotAll: true,
    );

    for (final match in regex.allMatches(jsonString)) {
      String? text = match.group(0);
      if (text == null) continue;

      Color? color;
      FontWeight? fontWeight;

      // 键名 - 绿色
      if (match.group(1) != null &&
          match.start > 0 &&
          jsonString[match.start - 1] == '"') {
        color = themeColors['key'];
        fontWeight = FontWeight.bold;
      }
      // 字符串值 - 黄色
      else if (match.group(1) != null) {
        color = themeColors['string'];
      }
      // 数字 - 青色
      else if (match.group(2) != null) {
        color = themeColors['number'];
      }
      // 布尔值和null - 紫色
      else if (match.group(3) != null) {
        color = themeColors['boolean'];
      }
      // 括号和符号 - 高亮色
      else if (match.group(4) != null) {
        color = themeColors['punctuation'];
        fontWeight = FontWeight.bold;
      }

      children.add(TextSpan(
        text: text,
        style: TextStyle(
          color: color ?? themeColors['default'],
          fontWeight: fontWeight,
          fontSize: widget.fontSize,
        ),
      ));
    }

    return RichText(
      text: TextSpan(
        style: TextStyle(
          fontFamily: 'monospace',
          fontSize: widget.fontSize,
          color: themeColors['default'],
        ),
        children: children,
      ),
    );
  }

  Map<String, Color> _getThemeColors() {
    if (widget.theme == JsonViewerTheme.dark) {
      return {
        'key': Colors.greenAccent,
        'string': Colors.yellowAccent,
        'number': Colors.cyanAccent,
        'boolean': Colors.purpleAccent,
        'punctuation': Colors.white,
        'default': Colors.white70,
        'background': Colors.black87,
        'error': Colors.redAccent,
      };
    } else {
      return {
        'key': Colors.green,
        'string': Colors.brown,
        'number': Colors.blue,
        'boolean': Colors.purple,
        'punctuation': Colors.grey,
        'default': Colors.grey,
        'background': Colors.grey,
        'error': Colors.red,
      };
    }
  }

  @override
  Widget build(BuildContext context) {
    final themeColors = _getThemeColors();

    return Container(
      color: themeColors['background'],
      child: Column(
        children: [
          // 工具栏
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            decoration: BoxDecoration(
              color: themeColors['background']?.withOpacity(0.8),
              border: Border(
                bottom: BorderSide(
                  color: themeColors['punctuation']?.withOpacity(0.2) ??
                      Colors.grey,
                ),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  _errorMessage == null ? 'JSON 视图' : '解析错误',
                  style: TextStyle(
                    color: themeColors['default'],
                    fontWeight: FontWeight.bold,
                  ),
                ),
                IconButton(
                  icon: Icon(
                    _isCopied ? Icons.check : Icons.copy,
                    color: themeColors['default'],
                    size: 18,
                  ),
                  onPressed: _copyToClipboard,
                  tooltip: _isCopied ? '已复制' : '复制JSON',
                ),
              ],
            ),
          ),

          // 内容区域
          Expanded(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: SingleChildScrollView(
                  child: _errorMessage != null
                      ? Text(
                          _errorMessage!,
                          style: TextStyle(
                            color: themeColors['error'],
                            fontFamily: 'monospace',
                            fontSize: widget.fontSize,
                          ),
                        )
                      : _buildHighlightedJson(),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
